fn findGeoName = 
(
	local geoname = undefined
	for geo in geometry do (
		if (iskindof geo editable_mesh or 
			iskindof geo editable_poly or
			iskindof geo polymeshobject) and
			findstring geo.name "_" != undefined then
		geoname = geo.name
	)
	if geoname == undefined then messagebox("不能定位到导出路径")
	geoname
)

fn adjustPath path_name = 
(
	local ret_path = path_name
	local c = path_name.count
	--print path_name[c]
	if (path_name[c] == "\\" or 
		path_name[c] == "/") then
		(
			c = c - 1
			ret_path = substring path_name 1 c
		)
	--print ret_path
	return ret_path	
)

pre_objects = #()
utility exportUtil "古剑OL工具"
(
	local working = ""
	local config = (getFilenamePath (getMAXIniFile())) + "vconfig.ini"
	
	label lbl "路径" align:#left across:2 
	editText edt1 "" align:#right width:100 offset:[0, -1]
	checkbox chkExportCloth "导出布料" checked:false offset:[4, 0]
	--button btnMarkCol "标记碰撞"
	local outputPath = ""
	button btnConvertSkin "转为Skin动画"
	--button btnRetriveSche "获取Skin结构信息"
	--button btnCompareSche "对比Skin结构信息"
	--button btnUIEntityCfg "导出3D对话光照配置"
	on edt1 entered text do
	(
		setINISetting config "" "dir" text
		outputPath = edt1.text
	)

	on chk1 changed state do
	(
		setINISetting config "" "exporttexture" (state as string)
	)
	
	on chkExportCloth changed state do
	(
		setINISetting config "" "exportcloth" (state as string)
	)
	
	on btnMarkCol pressed do
	(
		markCollision()
	)
	
	on btnConvertSkin pressed do
	(
		--convertSkin()
	)
	
	on btnRetriveSche pressed do
	(
		pre_objects = retrieveSchematic false
	)
	on btnCompareSche pressed do
	(
		if pre_objects.count == 0 then
		(
			messagebox "无对比的Skin结构信息，请先获取Skin结构信息"
		)
		else
		(
			cur_objects = retrieveSchematic true
			diff_objects = compareSchematic pre_objects cur_objects
			print "SCHEMATIC DIFF RESULT:"
			--print "DIFF: IN BOTH"
			--for i = 1 to diff_objects.in_both.count do
			--(
			--	print diff_objects.in_both[i] as string
			--)
			local hasDiff = false
			print "DIFF: 只存在于前一文档"
			local s_out = "只存在于前一文档:\n"
			for i = 1 to diff_objects.in_prev_only.count do
			(
				local tmpStr = diff_objects.in_prev_only[i].name + "<====" +
				diff_objects.in_prev_only[i].parent_name
				print tmpStr
				s_out = s_out + diff_objects.in_prev_only[i].name + "\n"
				hasDiff = true
			)
			print "DIFF: 只存在当前一文档"
			s_out = s_out + "只存在当前一文档:\n"
			for i = 1 to diff_objects.in_last_only.count do
			(
				local tmpStr = diff_objects.in_last_only[i].name + "<====" +
				diff_objects.in_last_only[i].parent_name
				print tmpStr
				s_out = s_out + diff_objects.in_last_only[i].name + "\n"
				hasDiff = true
			)
			if hasDiff then
			(
				messagebox s_out
			)
		)
	)
	
	on btnUIEntityCfg pressed do
	(
		local f = getSaveFileName caption: "保存光照配置文件:" types:"LightCfg(*.xml)|*.xml|AllFiles(*.*)|*.*"
		
		if f != undefined then
			ExportUIEntityLightCfg( f )
	)
	
	fn beforeExport =
	(
		local nvcompress = pluginPaths.get(2) + "nvcompress.exe"
		local nvcompress1 = pluginPaths.get(2) + "nvcompress1.exe"
		if doesFileExist nvcompress then (
			if not chk1.state then renameFile nvcompress nvcompress1
		)
		max modify mode
	)
	
	fn afterExport =
	(
		local nvcompress = pluginPaths.get(2) + "nvcompress.exe"
		local nvcompress1 = pluginPaths.get(2) + "nvcompress1.exe"
		if doesFileExist nvcompress1 then (
			if not chk1.state then renameFile nvcompress1 nvcompress
		)
		max utility mode
	)
		
	rollout rollShareNPC "体型"
	(
		label lbl "路径" align:#left across:2 
		editText edtNPC "" align:#right width:100 offset:[0, -1]
		button btnBatchModel "批量模型"
		button btnSingleAnim "单个动画"
		button btnBatchAnim "批量动画"
		checkbox chkAnimMoveBF "Forward/Backword" checked:hkSceneExportUtility.animMoveBackFor offset:[4, 0]
		checkbox chkAnimMoveUD "Up/Down" checked:hkSceneExportUtility.animMoveUpDown offset:[4, 0]
		checkbox chkAnimMoveLR "Right/Left" checked:hkSceneExportUtility.animMoveLeftRight offset:[4, 0]
		checkbox chkAnimMoveT  "Turning" checked:hkSceneExportUtility.animMoveTurn offset:[4, 0]

		button btnSaveMovePosFilter "位移保存"

		button btnMatchBone "匹配骨骼结构"
		label lblAll "路径2" align:#left across:2 
		editText edtSrcPath "" align:#right width:100 offset:[0, -1]
		checkbox chkExportSke "导出骨骼" checked:false offset:[4, 0]
		button btnBatchSingleSkeAndAnim "批量单个体型"
		button btnBatchSkeAndAnim "批量所有体型"
		
		local srcPath = ""
		local NPCName = ""
		
		on edtNPC entered text do
		(
			fileProperties.deleteProperty #custom "npcpath"
			fileProperties.addProperty #custom "npcpath" text
			NPCName = edtNPC.text
		)
		
		fn refreshPath = 
		(
			local pathid = fileProperties.findProperty #custom "npcpath"
			if pathid != 0 then (
				edtNPC.text = fileProperties.getPropertyValue #custom pathid
			)
			NPCName = edtNPC.text
			
			pathid = fileProperties.findProperty #custom "srcpath"
			if pathid != 0 then (
				edtSrcPath.text = fileProperties.getPropertyValue #custom pathid
			)
			srcPath = edtSrcPath.text
		)
		
		on  edtSrcPath entered text do
		(
			fileProperties.deleteProperty #custom "srcpath"
			fileProperties.addProperty #custom "srcpath" text
			srcPath = edtSrcPath.text
		)
		
		on rollShareNPC open do
		(
			refreshPath()
		)
		
		fn pathgen geoname =
		(
			adjustPath outputPath + "\\characters\\" + NPCName + "\\models\\" + geoname + "\\" + geoname + ".model"
		)
		
		on btnBatchModel pressed do
		(
			refreshPath()
			if outputPath == "" then
				messagebox("工作路径未设置")
			else if NPCName == "" then
				messagebox("体型路径未设置")
			else 
			(
				for geo in geometry do 
				(
					if isExportType geo then 
					(
						select geo
						
						local filename = outputPath + "\\characters\\" + 
							NPCName + "\\models\\" + geo.name + ".model"
						local dir = getFilenamePath filename
						if not isDirectoryWriteable dir then makeDir dir all:true
						local option = "
						harvestingOptions {
							grabBones 1 
							grabLights 0
							grabMaterials 1 
							grabNormals 1
							grabTangents 1
							grabColors 1
							gragUVs 1 
							uvChannel_diffuse \"1\"
							uvChannel_lightmap \"AUTO\"
						}
						optimizations {removeUnskinnedLeafBones 1}
						miscellaneous {exportAnimAlongWithModel 0} 
						postExportOptions {displayViewer 0 extractAndCopyTextures 1 projRelativeTexturePath 0 textureSubdir \"..\\textures\\\"}
						"
						exportVisionFileEx filename type:"Model" options:option noprompt:true exportSelected:true

						if chkExportCloth.checked then 
						(
							hkSceneExportUtility.environmentVariables = ("ModelPath=" + filename)
							hkSceneExportUtility.useOptionsFile = false
							hkSceneExportUtility.exportScene true
							hkSceneExportUtility.environmentVariables = ("ModelPath=\"\"")
						)
					)
				)	
			)
		)
		
		fn exportAnim checkCustom = 
		(
			local originFileName = getFilenameFile maxFileName
			local nameLength = originFileName.count
			local finalFileName = originFileName
			local useCustom = false
			local swordLight = false
			local pos = findString finalFileName "$"
			if pos != undefined then (
				swordLight = true
				finalFileName = replace finalFileName pos 1 ""
			)
			pos = findString finalFileName "%"
			if pos != undefined then (
				useCustom = true
				finalFileName = replace finalFileName pos 1 ""
			)
			local filename = adjustPath outputPath + "\\characters\\" + 
				NPCName + "\\anims\\" + finalFileName + ".hka"
			print filename
			local dir = getFilenamePath filename
			if not isDirectoryWriteable dir then makeDir dir all:true
			hkSceneExportUtility.useOptionsFile = false
			if (useCustom == false and checkCustom == true) then
			(
				hkSceneExportUtility.useOptionsFile = true
				hkSceneExportUtility.optionsFile = "C:\\Program Files\\Havok\\HavokContentTools\\configurations\\角色动画（无位移）.hko"
				if swordlight then
					hkSceneExportUtility.optionsFile = "C:\\Program Files\\Havok\\HavokContentTools\\configurations\\角色动画（有位移 刀光）.hko"
			)

			hkSceneExportUtility.environmentVariables = ("AurogonPath=" + filename)
			hkSceneExportUtility.exportScene true
			hkSceneExportUtility.environmentVariables = ("AurogonPath=\"\"")
		)
		
		on btnSingleAnim pressed  do
		(
			refreshPath()
			if outputPath == "" then
				messagebox("工作路径未设置")
			else if NPCName == "" then
				messagebox("体型路径未设置")
			else
				exportAnim true
		)

		on btnSaveMovePosFilter pressed do
		(

			hkSceneExportUtility.animMoveUpDown = chkAnimMoveUD.checked
			hkSceneExportUtility.animMoveBackFor = chkAnimMoveBF.checked
			hkSceneExportUtility.animMoveLeftRight = chkAnimMoveLR.checked
			hkSceneExportUtility.animMoveTurn = chkAnimMoveT.checked
			hkSceneExportUtility.saveFilterConfiguration true
		)		

		fn setMoveAminCheckBox = 
		(
			chkAnimMoveUD.checked = hkSceneExportUtility.animMoveUpDown
			chkAnimMoveBF.checked = hkSceneExportUtility.animMoveBackFor
			chkAnimMoveLR.checked = hkSceneExportUtility.animMoveLeftRight
			chkAnimMoveT.checked  =	hkSceneExportUtility.animMoveTurn
		)
		--callbacks.removescripts #filePostOpenProcess id:#my_postload
		--callbacks.addScript #filePostOpenProcess "setMoveAminCheckBox()" id:#jbwRender
		--callbacks.addscript #filePostOpenProcess "setMoveAminCheckBox()" id:#my_postload

		on btnBatchAnim pressed  do
		(
			refreshPath()
			if outputPath == "" then
				messagebox("工作路径未设置")
			else if NPCName == "" then
				messagebox("体型路径未设置")
			else (
				setquietmode true
				for f in getfiles (maxFilePath + "\\*.max") do (
					loadMaxFile f usefileunits:true
					exportAnim true
				)
				setquietmode false
			)
		)
		
		fn exportSkeleton filePath exportPath = 
		(
			setquietmode true
			loadMaxFile filePath usefileunits:true
			local dir = getFilenamePath exportPath
			if not isDirectoryWriteable dir then makeDir dir all:true
			hkSceneExportUtility.useOptionsFile = true
			hkSceneExportUtility.optionsFile = "C:\\Program Files\\Havok\\HavokContentTools\\configurations\\角色模型.hko"	
			hkSceneExportUtility.environmentVariables = ("AurogonPath=" + exportPath)
			hkSceneExportUtility.exportScene true
			hkSceneExportUtility.environmentVariables = ("AurogonPath=\"\"")
			setquietmode false
		)
		
		fn exportAnimRecur curPath interPath =
		(
			local dir_array = GetDirectories (curPath+"/*")
			for d in dir_array do
			  exportAnimRecur d interPath
			
			for f in getfiles (curPath + "\\*.max") do (
				loadMaxFile f usefileunits:true
				exportAnim true
				
			)
		)
		
		on btnBatchSingleSkeAndAnim pressed  do
		(
			refreshPath()
			if outputPath == "" then
				messagebox("工作路径未设置")
			else if NPCName == "" then
				messagebox("体型路径未设置")
			else if srcPath == "" then
				messagebox("体型路径2未设置")
			else (
				local rootPath = srcPath + "\\" + NPCName
				local findSkeleton = true

				local interPath = NPCName
				if (chkExportSke.checked) then
				(
					local exportPath = adjustPath outputPath + "\\characters\\" + 
					interPath + "\\" + interPath +　".hks"
					local filename = rootPath + "\\" + interPath + "_skin.max"
					if (doesFileExist filename) then
						exportSkeleton filename exportPath
					else
					(
						messagebox(interPath + "骨骼文件不存在")
						findSkeleton = false						
					)
				)
				
				if (findSkeleton) then
				(
					setquietmode true
					exportAnimRecur rootPath NPCName
					setquietmode false
				)
				else
					messagebox("请配置骨骼完成后重试")
			)
		)
		
		on btnBatchSkeAndAnim pressed  do
		(
			refreshPath()
			if outputPath == "" then
				messagebox("工作路径未设置")
			else if srcPath == "" then
				messagebox("体型路径2未设置")
			else (				
				local dir_array = GetDirectories (srcPath+"/*")
				local findSkeleton = true
				
				if dir_array.count == 0 then
					messagebox("体型路径2下无目录，请检查是否设置正确！")
				
				--先判断骨骼文件是否存在
				for d in dir_array do(
					tokens = filterString d "\\" splitEmptyTokens:false
					local interPath = tokens[tokens.count]
					if (chkExportSke.checked) then
					(
						local exportPath = adjustPath outputPath + "\\characters\\" + 
						interPath + "\\" + interPath +　".hks"
						local filename = d + "\\" + interPath + "_skin.max"
						if doesFileExist filename then
							exportSkeleton filename exportPath
						else
						(
							messagebox(interPath + "骨骼文件不存在")
							findSkeleton = false						
						)
					)
				)
				
				if (findSkeleton) then
				(
					--再导出所有动画
					for d in dir_array do(
						tokens = filterString d "\\" splitEmptyTokens:false
						local interPath = tokens[tokens.count]
						
						NPCName = interPath
						setquietmode true
						exportAnimRecur d interPath
						setquietmode false
					)
				)
				else
					messagebox("请配置骨骼完成后重试")

			)
		)
		
		rollout boxCreator "匹配骨骼结构"
		(
			--define an edittextwith width 100 and the label on top:
			label l1 "输入需导入动作中的骨骼名字，每行一个"
			label l2 "此操作比较危险，注意备份文件"
			edittext node1 fieldWidth:200
			edittext node2 fieldWidth:200
			edittext node3 fieldWidth:200
			edittext node4 fieldWidth:200
			edittext node5 fieldWidth:200
			edittext node6 fieldWidth:200
			edittext node7 fieldWidth:200
			edittext node8 fieldWidth:200
			edittext node9 fieldWidth:200
			edittext node10 fieldWidth:200
			edittext node11 fieldWidth:200
			edittext node12 fieldWidth:200
			edittext node13 fieldWidth:200
			edittext node14 fieldWidth:200
			edittext node15 fieldWidth:200
			edittext node16 fieldWidth:200
			edittext node17 fieldWidth:200
			edittext node18 fieldWidth:200
			edittext node19 fieldWidth:200
			edittext node20 fieldWidth:200
			button okbutton "确定"
			--If the user entered a new name...
			on okbutton pressed do
			(
				setquietmode true
				local nameArray = #()
				if node1.text != "" then appendIfUnique nameArray node1.text
				if node2.text != "" then appendIfUnique nameArray node2.text
				if node3.text != "" then appendIfUnique nameArray node3.text
				if node4.text != "" then appendIfUnique nameArray node4.text
				if node5.text != "" then appendIfUnique nameArray node5.text
				if node6.text != "" then appendIfUnique nameArray node6.text
				if node7.text != "" then appendIfUnique nameArray node7.text
				if node8.text != "" then appendIfUnique nameArray node8.text
				if node9.text != "" then appendIfUnique nameArray node9.text
				if node10.text != "" then appendIfUnique nameArray node10.text
				if node11.text != "" then appendIfUnique nameArray node11.text
				if node12.text != "" then appendIfUnique nameArray node12.text
				if node13.text != "" then appendIfUnique nameArray node13.text
				if node14.text != "" then appendIfUnique nameArray node14.text
				if node15.text != "" then appendIfUnique nameArray node15.text
				if node16.text != "" then appendIfUnique nameArray node16.text
				if node17.text != "" then appendIfUnique nameArray node17.text
				if node18.text != "" then appendIfUnique nameArray node18.text
				if node19.text != "" then appendIfUnique nameArray node19.text
				if node20.text != "" then appendIfUnique nameArray node20.text

				if nameArray.count == 0 then
					messagebox("请输入至少一个骨骼名")
				else (
					local skinFile = maxFileName
					local skinFileFullpath = maxFilePath + maxFileName
					for f in getfiles (maxFilePath + "\\*.max") do (
						local animFile = filenameFromPath f
						if skinFile != animFile then (
							loadMaxFile f usefileunits:true
							mergeMAXFile skinFileFullpath nameArray #skipDups #alwaysReparent quiet:true
							saveMaxFile f quiet:true
						)
					)
					loadMaxFile skinFileFullpath usefileunits:true
					setquietmode false
				)
			)
		)
		
		on btnMatchBone pressed  do
		(
			local curFile = maxFileName
			createDialog boxCreator 300 800 --create a Dialog from the rollout 
		)

		rollout rollModifyMax "修改骨骼"
		(
			label lblName "挂载点" align:#left across:2 
			editText edtDummyName "" align:#right width:100 offset:[0, -1]
			checkbox chkForceOperate "强制操作" checked:false offset:[4, 0]
			button btnAddDummy "添加Dummy点"
			button btnModifyDummy "修改Dummy点"
			button btnDeleteDummy "删除Dummy点"
			button btnAddAll "一键添加Root和*origin"
			button btnAddRoot "单个添加Root和*origin"
			button btnCopy "计算*origin"
			checkbox chkUseBF "Forward/Backword" checked:false offset:[4, 0]
			checkbox chkUseLR "Right/Left" checked:false offset:[4, 0]
			checkbox chkUseT "Turning" checked:false offset:[4, 0]
			checkbox chkUseZ "是否垂直跟随" checked:false offset:[4, 0]
			label lblName2 "垂直跟随距离:" align:#left
			editText edtZValue "" align:#left width:100 offset:[0, -1]
			button btnResetOrigion "重置*origin"
			
			local dummyName = ""
			local isForcedOperate = false
			local dummyTrans = (matrix3 [1,0,0] [0,1,0] [0,0,1] [0,0,0])
			local dummyParentName = ""
			local dummyChildrenName = #()
			
			fn getPath = 
			(
				refreshPath()
				if srcPath == "" then
				(
					messagebox("体型路径2未设置")
					return ""
				)
				rootPath = srcPath
				if NPCName == "" then
				(
					messagebox("体型路径未设置")
					return ""
				)
				rootPath = rootPath + "\\" + NPCName
				
				return rootPath
			)
			
			fn operateRecur curPath operator = 
			(
				local dir_array = GetDirectories (curPath+"/*")
				for d in dir_array do
				  operateRecur d operator
				
				for f in getfiles (curPath + "\\*.max") do (
					loadMaxFile f usefileunits:true
					if operator == "add" then
					(
						tmpNode = getnodebyname dummyName
						if tmpNode == undefined then
						(
							local op = "Dummy name:\"" + dummyName + "\""
							execute op
							tmpNode = getnodebyname dummyName
							
							setUserProp tmpNode "generated" 1
						)
						else
							continue
						tmpParentNode = getnodebyname dummyParentName
						tmpNode.parent = tmpParentNode
						if not tmpNode.parent == undefined then
							tmpNode.transform = dummyTrans * tmpNode.parent.transform
						else
							tmpNode.transform = dummyTrans
						for childName in dummyChildrenName do
						(
							tmpChildNode = getnodebyname childName
							tmpChildNode.parent = tmpNode
						)
						
						
					)
					else if operator == "modify" then
					(
						tmpNode = getnodebyname dummyName
						if tmpNode == undefined then
							continue
						if getUserProp tmpNode "generated" == undefined and not isForcedOperate then
							continue
						tmpParentNode = getnodebyname dummyParentName
						tmpNode.parent = tmpParentNode
						if not tmpNode.parent == undefined then
							tmpNode.transform = dummyTrans * tmpNode.parent.transform
						else
							tmpNode.transform = dummyTrans
						for childName in dummyChildrenName do
						(
							tmpChildNode = getnodebyname childName
							tmpChildNode.parent = tmpNode
						)
						
					)
					else if operator == "delete" then
					(
						tmpNode = getnodebyname dummyName
						if tmpNode == undefined then
							continue
						if getUserProp tmpNode "generated" == undefined and not isForcedOperate then
							continue

						for child in tmpNode.children do
							child.parent = tmpNode.parent
						delete tmpNode
					)
					else 
						messagebox("错误的operator！")
					
					saveMaxFile f
				)
			)
			
			on btnAddDummy pressed do
			(
				local rootPath = getPath()
				if edtDummyName.text == "" then
					messagebox("挂载点未设置")
				else if not isDirectoryWriteable rootPath then
					messagebox(rootPath + "路径不存在")
				else
				(
					local filename = rootPath + "\\" + NPCName + "_skin.max"
					local dName = edtDummyName.text
					if doesFileExist filename then
					(
						saveMaxFile (maxFilePath + maxFileName)
						setquietmode true
						loadMaxFile filename usefileunits:true
						dummyNode = getnodebyname dName
						if dummyNode == undefined then
						(
							setquietmode false
							messagebox("挂载点" + dName + "未在骨骼文件中找到！")
						)
						else
						(
							dummyName = dName
							isForcedOperate = chkForceOperate.checked
							dummyTrans = dummyNode.transform
							dummyParentName = ""
							if not dummyNode.parent == null then(
								dummyTrans *= inverse(dummyNode.parent.transform)
								dummyParentName = dummyNode.parent.name
							)
							dummyChildrenName = #()
							for child in dummyNode.children do
								append dummyChildrenName child.name
							
							operateRecur rootPath "add"
						)
						
						setquietmode false
					)
					else
						messagebox(NPCName + "骨骼文件不存在")
				)
			)
			
			on btnModifyDummy pressed do
			(
				local rootPath = getPath()
				if edtDummyName.text == "" then
					messagebox("挂载点未设置")
				else if not isDirectoryWriteable rootPath then
					messagebox(rootPath + "路径不存在")
				else
				(
					local filename = rootPath + "\\" + NPCName + "_skin.max"
					local dName = edtDummyName.text
					if doesFileExist filename then(
						saveMaxFile (maxFilePath + maxFileName)
						setquietmode true
						loadMaxFile filename usefileunits:true
						setquietmode false
						dummyNode = getnodebyname dName
						if dummyNode == undefined then
						(
							--setquietmode false
							messagebox("挂载点" + dName + "未在骨骼文件中找到！")
						)
						else
						(					
							if chkForceOperate.checked and not queryBox "真的要强制执行？" then
								return ""
							dummyName = edtDummyName.text
							isForcedOperate = chkForceOperate.checked
							dummyTrans = dummyNode.transform
							dummyParentName = ""
							if not dummyNode.parent == null then(
								dummyTrans *= inverse(dummyNode.parent.transform)
								dummyParentName = dummyNode.parent.name
							)
							dummyChildrenName = #()
							for child in dummyNode.children do
								append dummyChildrenName child.name
							
							setquietmode true
							operateRecur rootPath "modify"
							setquietmode false
						)
						
						setquietmode false
					)
					else
						messagebox(NPCName + "骨骼文件不存在")
				)
			)
			
			on btnDeleteDummy pressed do
			(				
				local rootPath = getPath()
				if edtDummyName.text == "" then
					messagebox("挂载点未设置")
				else if not isDirectoryWriteable rootPath then
					messagebox(rootPath + "路径不存在")
				else
				(
					if chkForceOperate.checked and not queryBox "真的要强制执行？" then
						return ""
					saveMaxFile (maxFilePath + maxFileName)
					dummyName = edtDummyName.text
					isForcedOperate = chkForceOperate.checked
					setquietmode true
					operateRecur rootPath "delete"
					setquietmode false
				)
			)
					
			fn exportAddAll curPath =
			(
				local dir_array = GetDirectories (curPath+"/*")
				for d in dir_array do
				  exportAddAll d
				
				for f in getfiles (curPath + "\\*.max") do (
					loadMaxFile f usefileunits:true
					if getnodebyname "Root" == undefined then
						Dummy pos:[0,0,0] name:"Root" boxSize:[20,20,20]
					if getnodebyname "*origin" == undefined then
						Dummy pos:[0,0,0] name:"*origin" boxSize:[10,10,10]
					$'*origin'.parent = $Root
					if getnodebyname "Bip01" != undefined then
						$Bip01.parent = $Root
					saveMaxFile f
					
				)
			)
			
			on btnAddAll pressed do
			(
				if not queryBox "真的要一键添加Root和*Origin点？" then
					return ""
				refreshPath()
				if srcPath == "" then
				(
					messagebox("体型路径2未设置")
					return ""
				)
				local dir_array = GetDirectories (srcPath+"/*")
				for d in dir_array do
				(
					setquietmode true
					exportAddAll d
					setquietmode false
				)
			)
						
			on btnAddRoot pressed do
			(
				if not queryBox "真的要添加Root和*Origin点？" then
					return ""
				if getnodebyname "Bip01" == undefined then
				(
					messagebox("没有找到Bip01点")
					return ""
				)
				if getnodebyname "Root" == undefined then
					Dummy pos:[0,0,0] name:"Root" boxSize:[20,20,20]
				if getnodebyname "*origin" == undefined then
					Dummy pos:[0,0,0] name:"*origin" boxSize:[10,10,10]
				$'*origin'.parent = $Root
				if getnodebyname "Bip01" != undefined then
					$Bip01.parent = $Root
			)

			on btnResetOrigion pressed do
			(
				fileProperties.deleteProperty #custom "motionusebf"
				fileProperties.deleteProperty #custom "motionuselr"
				fileProperties.deleteProperty #custom "motionuset"
				fileProperties.deleteProperty #custom "motionusez"
				chkUseBF.checked = false
				chkUseLR.checked = false
				chkUseT.checked = false
				chkUseZ.checked = false
				
				local rootBone = getnodebyname "*origin"
				print rootBone
				if undefined == rootBone then
					messagebox("未找到*origin!")
				else
				(
					deleteKeys rootBone #allKeys
					
					rootBone.rotation = (eulerAngles 0 0 0)
					rootBone.pos.x = 0
					rootBone.pos.y = 0
					rootBone.pos.z = 0
				)
			)
			
			on btnCopy pressed do
			(
				fileProperties.deleteProperty #custom "motionusebf"
				fileProperties.addProperty #custom "motionusebf" chkUseBF.checked
				fileProperties.deleteProperty #custom "motionuselr"
				fileProperties.addProperty #custom "motionuselr" chkUseLR.checked
				fileProperties.deleteProperty #custom "motionuset"
				fileProperties.addProperty #custom "motionuset" chkUseT.checked
				fileProperties.deleteProperty #custom "motionusez"
				fileProperties.addProperty #custom "motionuset" chkUseZ.checked
				
				if (not chkUseBF.checked) and (not chkUseLR.checked) and 
					(not chkUseT.checked) and (not chkUseZ.checked) then
					(
						messagebox("未启用任一轴向的位移!")
						return ""
					)

				myAnimationRange = animationRange.end
				rootBone = getnodebyname "*origin"
				bipBone = $Bip01
				sliderTime = 0
				toolMode.coordsys #world
				-- set key for bipBone
				with animate on
				(
					at time 0 (
						baseBipBoneRotAnim = bipBone.transform.rotation
						deltaZ = bipBone.transform.pos.z - rootBone.pos.z
					)
					for i = 0.0 to myAnimationRange by 1 do
					(
						at time i (
							if chkUseT.checked then
								rootBone.rotation = (eulerAngles 0 0 ((quatToEuler baseBipBoneRotAnim).z - (quatToEuler bipBone.transform.rotation).z))
							else
								rootBone.rotation = (eulerAngles 0 0 0)

							if chkUseLR.checked then
								rootBone.pos.x = bipBone.transform.pos.x
							else
								rootBone.pos.x = 0

							if chkUseBF.checked then
								rootBone.pos.y = bipBone.transform.pos.y
							else
								rootBone.pos.y = 0

							rootBone.pos.z = 0
							if (chkUseZ.checked) then (
								if (edtZValue.text.count != 0) then
									deltaZ = edtZValue.text as float
								rootBone.pos.z = bipBone.transform.pos.z - deltaZ
							)
						)
					)
				)
			)

			on rollModifyMax open do
			(
				local pathid = fileProperties.findProperty #custom "motionusebf"
				if pathid != 0 then (
					chkUseBF.checked = fileProperties.getPropertyValue #custom pathid
				)

				pathid = fileProperties.findProperty #custom "motionuselr"
				if pathid != 0 then (
					chkUseLR.checked = fileProperties.getPropertyValue #custom pathid
				)

				pathid = fileProperties.findProperty #custom "motionuset"
				if pathid != 0 then (
					chkUseT.checked = fileProperties.getPropertyValue #custom pathid
				)

				pathid = fileProperties.findProperty #custom "motionusez"
				if pathid != 0 then (
					chkUseZ.checked = fileProperties.getPropertyValue #custom pathid
				)
			)
		)
		
		on rollShareNPC open do
		(
			addRollout rollModifyMax rolledUp:true
			refreshPath()
		)
		
		on rollShareNPC close do
		(
			removeRollout rollModifyMax
		)
		
		on rollShareNPC rolledUp state do setINISetting config "" "rollShareNPC" (state as string)
	
	)

	fn fnTagLOD lodIndex = 
	(
		selArray = selection as array
		if selArray.count <= 0 or lodIndex > 3 or lodIndex < 0 then
		(
			messagebox "请选中一个Mesh对象!" title:"错误!"
			return false
		)

		curSel = selArray[1]

		arrNearClip = #(0, 300, 600, 1000)
		arrFarClip = #(300, 600, 1000, 100000)

		setUserProp curSel "vision_mesh_name" curSel.name
		setUserProp curSel "vision_mesh_nearClip" arrNearClip[lodIndex+1] as string
		setUserProp curSel "vision_mesh_farClip" arrFarClip[lodIndex+1] as string
		setUserProp curSel "vision_mesh_lodIndex" lodIndex as string
		setUserProp curSel "vision_export_as" "renderMesh"
	)

	rollout rollLODTagger "LOD标记工具"
	(
		button btnTagLodIndex0 "标记为-最高级"
		button btnTagLodIndex1 "标记为-中高级"
		button btnTagLodIndex2 "标记为-中低级"
		button btnTagLodIndex3 "标记为-最低级"
		
		on btnTagLodIndex0 pressed do
		(
			fnTagLOD 0
		)

		on btnTagLodIndex1 pressed do
		(
			fnTagLOD 1
		)

		on btnTagLodIndex2 pressed do
		(
			fnTagLOD 2
		)

		on btnTagLodIndex3 pressed do
		(
			fnTagLOD 3
		)
	)

	fn fnTagOcmmmmmm lodIndex = 
	(
		selArray = selection as array
		if selArray.count <= 0 then
		(
			messagebox "请选中一个Mesh对象!" title:"错误!"
			return false
		)

		curSel = selArray[1]

		setUserProp curSel "vision_export_as" "ocmmmmmm"
	)


	rollout rollOCMTagger "OCM标记工具"
	(
		button btnTagOcm "标记为OCM"
		
		on btnTagOcm pressed do
		(
			fnTagOcmmmmmm 1
		)
	)

		on exportUtil rolledUp state do setINISetting config "" "exportUtil" (state as string)
	
	fn ExportFOV filename = 
	(
	    local basePoint = $Camera001 --getNodeByName "Camera001"
	    if basePoint == undefined then 
	    (
	        messagebox "not find Node:Camera001!" title:"Warning!"
	    )
	    else
	    (
	        local xmlDoc = dotNetObject "system.xml.xmlDocument"
	        local xmlRoot = xmlDoc.CreateElement "Root" 
	        xmlDoc.AppendChild xmlRoot
	        
	        local xml2 = xmlDoc.CreateElement "CameraConfig" 
	        xmlRoot.AppendChild xml2
	
	        xml2.SetAttribute "rate" (frameRate as string)
	
	        local xmlpath = xmlDoc.CreateElement "CameraPath" 
	        xmlRoot.AppendChild xmlpath        
	        
	                
	        local beginPos
	        local beginTarget
	        local beginFov
	        local beginEuler
	        for i = 0 to animationRange.end  by 1 do
	        (
	            at time i(  
	                if i == 0 then
	                (
	                    beginPos = basePoint.position
	                    beginTarget = basePoint.target.position
	                    beginFov = basePoint.fov
	                    local _by = beginPos.x
	                    local _bx = -beginPos.y
	                    local _bz = beginPos.z
	                    local _bty = beginTarget.x
	                    local _btx = -beginTarget.y
	                    local _btz = beginTarget.z
	                    local bPos = (_bx as string) + "," + (_by as string)+ "," + (_bz as string)                    
	                    local bTar = (_btx as string) + "," + (_bty as string)+ "," + (_btz as string)      

						beginEuler = quatToEuler basePoint.transform.rotation       
						local _bYaw = beginEuler.z
						local _bPitch = beginEuler.y
						local _bRoll = beginEuler.x
						local bEuler = (_bYaw as string) + "," + (_bPitch as string)+ "," + (_bRoll as string)   

	                    xml2.SetAttribute "bPos" bPos
	                    xml2.SetAttribute "bTarget" bTar
	                    xml2.SetAttribute "bFov" (beginFov as string)
				        xmlRoot.SetAttribute "bEuler" bEuler
	                )
	                if i == animationRange.end then
	                (
	                    xml2.SetAttribute "total" (i as string)
	
	                    local duration = i * 1000.0/frameRate
	                    xml2.SetAttribute "duration" (duration as string)
	
	                )               
	                local xml1 = xmlDoc.CreateElement "Path" 
	                
	                
	                local p1 = basePoint.position - beginPos
	                local p2 = basePoint.target.position - beginTarget
	                local iby = p1.x * 100
	                local ibx = -p1.y * 100
	                local ibz = p1.z * 100
	                local ibty = p2.x * 100
	                local ibtx = -p2.y * 100
	                local ibtz = p2.z * 100
	                local _by =     iby as integer
	                local _bx =     ibx  as integer
	                local _bz =     ibz  as integer
	                local _bty =    ibty as integer
	                local _btx =    ibtx as integer
	                local _btz =    ibtz as integer
	                local pos = (_bx as string) + "," + (_by as string)+ "," + (_bz as string)                    
	                local tar = (_btx as string) + "," + (_bty as string)+ "," + (_btz as string)   
	                local iFov = (basePoint.fov - beginFov) * 100
	                local fov = iFov as integer

					local curEuler = quatToEuler basePoint.transform.rotation       
	
					local _bYaw = (curEuler.z - 180)*100 as integer
					local _bPitch = (90 - curEuler.x)*100 as integer
					local _bRoll = curEuler.y*100 as integer

					local euler = (_bYaw as string) + "," + (_bPitch as string)+ "," + (_bRoll as string)   

	                xml1.SetAttribute "p" pos
	                xml1.SetAttribute "tar" tar
	                xml1.SetAttribute "fov" (fov as string)
	                xml1.SetAttribute "euler" (euler as string)
	                
	                xmlpath.AppendChild xml1
	            )
	        )                   
	        xmlDoc.Save(filename)
	    )
	)

	fn ExportRoot filename = 
	(
	    local basePoint = $Root --getNodeByName "Camera001"
	    if basePoint == undefined then 
	    (
	        messagebox "not find Node:Root!" title:"Warning!"
	    )
	    else
	    (
	        local xmlDoc = dotNetObject "system.xml.xmlDocument"
	        local xmlRoot = xmlDoc.CreateElement "Root" 
	        xmlDoc.AppendChild xmlRoot      
	
	        local p = basePoint.pos
	        local x = -p.y
	        local y = p.x
	        local z = p.z
	        local _pos = (x as string) + "," + (y as string)+ "," + (z as string)  
	        xmlRoot.SetAttribute "root_pos" _pos
	        
	        local euler = quatToEuler basePoint.rotation
	        local ex = -euler.z
	        local ey = euler.y
	        local ez = euler.x

	        local _euler = (ex as string) + "," + (ey as string)+ "," + (ez as string)  
	        xmlRoot.SetAttribute "root_euler" _euler
	
	        $Root.pos = [0,0,0]
	        $Root.rotation = (eulerAngles 0 0 0)
	    )
	    xmlDoc.Save(filename)
	)
	
	rollout rollConsole "单机导出功能"
	(
		button btnFOV "导出相机位移2.0"
		
		on btnFOV pressed do
		(
			output_name = getSaveFileName caption:"fov" types:"CameraFOV (*.xml)|*.xml|All Files (*.*)|*.*|"
			if output_name != undefined then
				ExportFOV output_name
		)

		button btnRoot "导出root点位置并归零"
		on btnRoot pressed do
		(
			output_name = getSaveFileName caption:"root" types:"Root (*.xml)|*.xml|All Files (*.*)|*.*|"
			if output_name != undefined then
			    ExportRoot output_name
		)
	)

	on exportUtil open do
	(
		local v = getINISetting config "" "dir"
		if v != undefined then
		(
			edt1.text = v
			outputPath = edt1.text
		)
		v = getINISetting config "" "exporttexture"
		if v == "true" then chk1.state = true
		v = getINISetting config "" "exportcloth"
		if v == "true" then chkExportCloth.state = true
			
		addRollout rollShareNPC rolledUp:true
		addRollout rollLODTagger rolledUp:true
		addRollout rollOCMTagger rolledUp:true
		addRollout rollConsole rolledUp:true

		
		if getINISetting config "" "rollShareNPC" == "false" then rollShareNPC.open = false
		if getINISetting config "" "exportUtil" == "false" then exportUtil.open = false
	) 
	
	on exportUtil close do
	(
		removeRollout rollShareNPC
	)
	

)

fn setMoveAminCheckBox =
(
	exportUtil.rollShareNPC.chkAnimMoveUD.checked = hkSceneExportUtility.animMoveUpDown
	exportUtil.rollShareNPC.chkAnimMoveBF.checked = hkSceneExportUtility.animMoveBackFor
	exportUtil.rollShareNPC.chkAnimMoveLR.checked = hkSceneExportUtility.animMoveLeftRight
	exportUtil.rollShareNPC.chkAnimMoveT.checked = hkSceneExportUtility.animMoveTurn

	(
		local pathid = fileProperties.findProperty #custom "motionusebf"
		if pathid != 0 then (
			exportUtil.rollShareNPC.rollModifyMax.chkUseBF.checked = fileProperties.getPropertyValue #custom pathid
		)

		pathid = fileProperties.findProperty #custom "motionuselr"
		if pathid != 0 then (
			exportUtil.rollShareNPC.rollModifyMax.chkUseLR.checked = fileProperties.getPropertyValue #custom pathid
		)

		pathid = fileProperties.findProperty #custom "motionuset"
		if pathid != 0 then (
			exportUtil.rollShareNPC.rollModifyMax.chkUseT.checked = fileProperties.getPropertyValue #custom pathid
		)

		pathid = fileProperties.findProperty #custom "motionusez"
		if pathid != 0 then (
			exportUtil.rollShareNPC.rollModifyMax.chkUseZ.checked = fileProperties.getPropertyValue #custom pathid
		)
	)
)

callbacks.addscript #filePostOpenProcess "setMoveAminCheckBox()" id:#my_postload